package com.topic;

import com.constant.Constants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 通配符模式发送消息
 */
public class product {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.POST);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();
        //2.开启信道
        Channel channel = connection.createChannel();
        //3.声明交换机
        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC,true);
        //4.声明队列
        channel.queueDeclare(Constants.TOPIC_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.TOPIC_QUEUE2,true,false,false,null);
        //5.绑定交换机和队列
        channel.queueBind(Constants.TOPIC_QUEUE1,Constants.TOPIC_EXCHANGE,"*.a.*");
        channel.queueBind(Constants.TOPIC_QUEUE2,Constants.TOPIC_EXCHANGE,"*.*.b");
        channel.queueBind(Constants.TOPIC_QUEUE2,Constants.TOPIC_EXCHANGE,"c.#");
        //6.发送消息:
        //发送给q1:
        String msg = "hello direct,abc.a.c ";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"abc.a.c",null,msg.getBytes());
        //发送给q1,q2:
        String msg_b = "hello direct,ab.a.b ";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"ab.a.b",null,msg_b.getBytes());
        //发送给q2:
        String msg_c = "hello direct,c.bb.c ";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"c.bb.c",null,msg_c.getBytes());

        System.out.println("发送消息成功!");
        //7.关闭连接
        channel.close();
        connection.close();
    }
}
